﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.BusinessEntity.YunZhiJia;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.ServiceHelper;
using Kingdee.BOS.Util;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace LiMinCRMPlugin.InterfaceDocking
{
    /// <summary>
    /// 财务应收审核插件
    /// </summary>
    /// <remarks>
    /// 功能：财务应收在审核后自动传到CRM(标准应收单、转销为false)。
    /// 创建人：wzx
    /// 创建日期：2024.7.23
    /// 修改信息（1）：修改人，修改日期，修改内容
    /// </remarks>
    [Description("财务应收审核同步至CRM")]
    [HotUpdate]
    public class FinancialReceivablesToCRM : AbstractOperationServicePlugIn
    {
        //OnPreparePropertys 数据加载前，确保需要的属性被加载
        public override void OnPreparePropertys(PreparePropertysEventArgs e)
        {
            base.OnPreparePropertys(e);
            //源单内码
            e.FieldKeys.Add("FBILLIDSRC");
            //立账类型
            e.FieldKeys.Add("FSetAccountType");
            //单据类型
            e.FieldKeys.Add("FBillTypeID");
            //业务类型
            e.FieldKeys.Add("FBUSINESSTYPE");
            //CRM编码
            e.FieldKeys.Add("F_DEV_CRMNumber");
            //销售订单编码
            e.FieldKeys.Add("F_DEV_OrderNo");


            //业务日期
            e.FieldKeys.Add("FDate");
            //销售组织
            e.FieldKeys.Add("FSALEORGID");
            //客户
            e.FieldKeys.Add("FCUSTOMERID");
            //销售部门
            e.FieldKeys.Add("FSALEDEPTID");
            //交货方式
            e.FieldKeys.Add("F_RDLV_HeadDeliveryWay");
            //承运商
            e.FieldKeys.Add("F_RDLV_CarrierID");
            //运输单号
            e.FieldKeys.Add("F_RDLV_CarriageNO");
            //交货地点
            e.FieldKeys.Add("F_RDLV_HeadLocationId");
            //备注
            e.FieldKeys.Add("FAR_Remark");
            //发货部门
            e.FieldKeys.Add("F_RDLV_DeliveryDeptID");
            //仓管员
            e.FieldKeys.Add("F_RDLV_StockerID");
            //销售员
            e.FieldKeys.Add("F_DEV_Saler");
            //收款条件
            e.FieldKeys.Add("FPayConditon");
            //核销方式
            e.FieldKeys.Add("F_RDLV_WriteOff");
            //是否调货订单
            e.FieldKeys.Add("F_RDLV_Seasoning");
            //是否淡储
            e.FieldKeys.Add("F_DEV_Survive");
            //是否定制
            e.FieldKeys.Add("F_DEV_Offset");
            //结算方式
            e.FieldKeys.Add("FSettleTypeID");
            //库存组织
            e.FieldKeys.Add("F_RDLV_NewStockOrgId");



            //结算组织
            e.FieldKeys.Add("FSETTLEORGID");
            //币别
            e.FieldKeys.Add("FCURRENCYID");

            //物料编码
            e.FieldKeys.Add("FNumber");
            //批号
            e.FieldKeys.Add("FLot");
            //含税单价
            e.FieldKeys.Add("FTaxPrice");
            //是否赠品
            e.FieldKeys.Add("FIsFree");
            //税率
            e.FieldKeys.Add("FEntryTaxRate");
            //销售数量
            e.FieldKeys.Add("FSalQty");
            //价税合计
            e.FieldKeys.Add("FALLAMOUNTFOR_D");
            //仓库
            e.FieldKeys.Add("F_RDLV_Stock");
            //库存组织
            e.FieldKeys.Add("FSTOCKORGID");
            //结算组织
            e.FieldKeys.Add("FSETTLEORGID");
            //销售单位
            e.FieldKeys.Add("FSalUnitId");
            //计价单位
            e.FieldKeys.Add("FPRICEUNITID");
            //源单标识
            e.FieldKeys.Add("F_SVZW_Assistant_qtr_dvn");
            //源单编码
            e.FieldKeys.Add("FUseOrgId");
            //同步CRM状态
            e.FieldKeys.Add("F_DEV_FSTATUS");
            //源单类型
            e.FieldKeys.Add("FSOURCETYPE");
            //源单单据类型
            e.FieldKeys.Add("FSOURCEBILLTYPEID");


            //销售类型
            e.FieldKeys.Add("F_DEV_OrderType");
            //计价数量(暂估数量)
            e.FieldKeys.Add("FPriceQty");
            //销售基本数量
            e.FieldKeys.Add("FSalBaseQty");

            //进仓编码
            e.FieldKeys.Add("F_RDLV_JCBH");
            //销售主体
            e.FieldKeys.Add("F_RDLV_saleBody");
            //出库单号
            e.FieldKeys.Add("FOUTSTOCKID");

            //形式发票
            e.FieldKeys.Add("F_QLTK_InvoiceNo");
            //合同号
            e.FieldKeys.Add("F_QLTK_ContractNumber");
            //行号
            e.FieldKeys.Add("FSeq");
            //海空运费
            e.FieldKeys.Add("F_QLTK_SeaAirFreight");
            //保费
            e.FieldKeys.Add("F_QLTK_PREMIUM");
            //佣金
            e.FieldKeys.Add("F_QLTK_Commission");
            //其他1
            e.FieldKeys.Add("F_QLTK_Other1");
            //是否返利
            e.FieldKeys.Add("F_QLTK_WhetherToRebate");
            //计划跟踪号
            e.FieldKeys.Add("F_QLTK_MtoNo");

            //汇率
            e.FieldKeys.Add("FExchangeRate");
            //销售订单行号
            e.FieldKeys.Add("FORDERENTRYSEQ");
            //销售订单行内码
            e.FieldKeys.Add("FORDERENTRYID");
            //出库单号(二开)
            e.FieldKeys.Add("F_RDLV_OutBillNo");
            //发货组织
            e.FieldKeys.Add("F_RDLV_NewStockOrgId");


            //通知单编码
            e.FieldKeys.Add("F_QLTK_NoticeNo");
            //折扣率
            e.FieldKeys.Add("FEntryDiscountRate");
            //折扣额
            e.FieldKeys.Add("FDISCOUNTAMOUNTFOR");

            //付款方式
            e.FieldKeys.Add("F_QLTK_PaymentMethod");
            //价税合计(单据头)
            e.FieldKeys.Add("FALLAMOUNTFOR");
            //源单编号
            e.FieldKeys.Add("FSourceBillNo");

            //转销
            e.FieldKeys.Add("FIsWriteOff");
            //收款组织
            e.FieldKeys.Add("FPAYORGID");
            //物料
            e.FieldKeys.Add("FMATERIALID");
            


        }
        /// <summary>
        /// 事务结束后事件
        /// </summary>
        /// <param name="e"></param>
        public override void EndOperationTransaction(EndOperationTransactionArgs e)
        {
            base.EndOperationTransaction(e);
            string InvokeType = "";
            if (this.FormOperation.Operation.ToUpper() == "AUDIT")
            {
                InvokeType = "财务应收审核自动上传CRM";
            }
            else if (this.FormOperation.Operation.ToUpper() == "REUPLOADPROVISIONALRECEIVABLES")
            {
                InvokeType = "财务应收手工上传CRM";
            }
            //读取全部的单据,for循环,转换成DynamicObject类型
            foreach (DynamicObject entity in e.DataEntitys)
            {
                string FSetAccountType = entity["FSetAccountType"].ToString();//立账类型
                string SOURCETYPE = "";//源单类型 
                string FID = entity["ID"].ToString();
                string FBillNo = entity["BillNo"].ToString();
                string StockOrgNo = "";
                DynamicObject BillType = entity["BillTypeID"] as DynamicObject;//单据类型
                string BillTypeId = "";//单据类型内码
                string BillTypeNo = "";//单据类型编码
                string BillTypeName = "";
                if (BillType != null)
                {
                    BillTypeId = Convert.ToString(BillType["ID"]);//单据类型内码
                    BillTypeNo = Convert.ToString(BillType["Number"]);//单据类型编码
                    BillTypeName = Convert.ToString(BillType["Name"]);//单据类型名称
                }
                string FIsWriteOff = Convert.ToString(entity["IsWriteOff"]);//转销

                int custId = 0;//客户内码
                DynamicObject CustomerInternal = entity["CUSTOMERID"] as DynamicObject;//客户
                if (CustomerInternal != null)
                {
                    custId = Convert.ToInt32(CustomerInternal["Id"]);
                 
                }

                string sqlcust = @"/*dialect*/  select F_QLTK_Internal from T_BD_CUSTOMER where fcustid='" + custId + "' ";
                DataTable dt_In = DBUtils.ExecuteDataSet(this.Context, sqlcust).Tables[0];

                string Internal = dt_In.Rows[0][0].ToString();

                
                
                //增加不是内部结算的
                if (FSetAccountType == "3"&& (BillTypeNo == "YSD01_SYS" || BillTypeNo== "YSD05_SYS") && FIsWriteOff=="False" && Internal=="0")//财务应收、标准应收、非转销
                {
                    DynamicObject SettleOrg = entity["SETTLEORGID"] as DynamicObject;//结算组织
                    string SettleOrgId = "";//结算组织内码
                    string SettleOrgNo = "";//结算组织编码
                    string SettleOrgName = "";
                    if (SettleOrg != null)
                    {
                        SettleOrgId = Convert.ToString(SettleOrg["ID"]);//结算组织内码
                        SettleOrgNo = Convert.ToString(SettleOrg["Number"]);//结算组织编码
                        SettleOrgName = Convert.ToString(SettleOrg["Name"]);//结算组织名称
                    }
                    //判断组织是否推送CRM
                    string sqlOrg = @"/*dialect*/  select F_QLTK_WhetherPushCRM from T_ORG_Organizations where FOrgID='" + SettleOrgId + "' ";
                    DataTable dt_Org = DBUtils.ExecuteDataSet(this.Context, sqlOrg).Tables[0];
                    string WhetherPushCRM = dt_Org.Rows[0][0].ToString();

                    DynamicObject PayOrg = entity["FPAYORGID"] as DynamicObject;//收款组织
                    string PayOrgId = "";//收款组织内码
                    string PayOrgNo = "";//收款组织编码
                    string PayOrgName = "";
                    if (PayOrg != null)
                    {
                        PayOrgId = Convert.ToString(PayOrg["ID"]);//收款组织内码
                        PayOrgNo = Convert.ToString(PayOrg["Number"]);//收款组织编码
                        PayOrgName = Convert.ToString(PayOrg["Name"]);//收款组织名称
                    }
                    DynamicObject SaleOrg = entity["SALEORGID"] as DynamicObject;//销售组织
                    string SaleOrgId = "";//销售组织内码
                    string SaleOrgNo = "";//销售组织编码
                    string SaleOrgName = "";
                    if (SaleOrg != null)
                    {
                        SaleOrgId = Convert.ToString(SaleOrg["ID"]);//销售组织内码
                        SaleOrgNo = Convert.ToString(SaleOrg["Number"]);//销售组织编码
                        SaleOrgName = Convert.ToString(SaleOrg["Name"]);//销售组织名称
                    }

                    
                    string BUSINESSTYPE = Convert.ToString(entity["FBUSINESSTYPE"]);//业务类型
                    string OrderNo = Convert.ToString(entity["F_DEV_OrderNo"]);//销售订单编码

                    string FSTATUS = Convert.ToString(entity["F_DEV_FSTATUS"]);//同步CRM状态 空-未同步，成功-同步成功，失败-同步失败
                    DynamicObject SaleDept = entity["SALEDEPTID"] as DynamicObject;//销售部门
                    int SaleDeptId = 0;
                    string SaleDeptNo = "";
                    if (SaleDept != null)
                    {
                        SaleDeptId = Convert.ToInt32(SaleDept["ID"].ToString());
                        SaleDeptNo = SaleDept["Number"].ToString();
                    }
                    DynamicObject Saler = entity["F_DEV_Saler"] as DynamicObject;//销售员
                    int SalerId = 0;
                    string SalerNo = "";
                    if (Saler != null)
                    {
                        SalerId = Convert.ToInt32(Saler["ID"].ToString());
                        SalerNo = Saler["FStaffNumber"].ToString();
                    }

                    #region 根据销售员查询用户账号
                    int CONTACTOBJECTID = 0;//联系对象内码
                    string SQLCONTACTOBJECT = string.Format(@"/*dialect*/select FID from V_BD_CONTACTOBJECT
where FNUMBER='{0}' ", SalerNo);
                    DataTable dtCONTACTOBJECT = DBUtils.ExecuteDataSet(this.Context, SQLCONTACTOBJECT).Tables[0];
                    if (dtCONTACTOBJECT.Rows.Count > 0)
                    {
                        CONTACTOBJECTID = Convert.ToInt32(dtCONTACTOBJECT.Rows[0]["FID"]);
                    }
                    string UserAccount = "";//用户账号
                    string SQLUser = string.Format(@"/*dialect*/select FUSERACCOUNT from T_SEC_user where FLINKOBJECT='{0}' ", CONTACTOBJECTID);
                    DataTable dtUser = DBUtils.ExecuteDataSet(this.Context, SQLUser).Tables[0];
                    if (dtUser.Rows.Count > 0)
                    {
                        UserAccount = dtUser.Rows[0]["FUSERACCOUNT"].ToString();
                    }
                    #endregion

                    string FDATE = entity["DATE"].ToString();//业务日期

                    DynamicObject HeadLocation = entity["F_RDLV_HeadLocationId"] as DynamicObject;//交货地点
                    string HeadLocationId = "";
                    string HeadLocationNo = "";
                    if (HeadLocation != null)
                    {
                        HeadLocationId = HeadLocation["ID"].ToString();
                        HeadLocationId = HeadLocation["Number"].ToString();
                    }
                    int Seasoning = 0;
                    int Survive = 0;
                    if (!entity["F_RDLV_Seasoning"].IsNullOrEmptyOrWhiteSpace())
                    {
                        Seasoning = Convert.ToInt32(entity["F_RDLV_Seasoning"]);//是否调货订单
                    }
                    if (!entity["F_DEV_Survive"].IsNullOrEmptyOrWhiteSpace())
                    {
                        Survive = Convert.ToInt32(entity["F_DEV_Survive"].ToString());//是否淡储
                    }


                    string FAR_Remark = entity["Remark"].ToString().Replace("%", "%25");//备注
                    FAR_Remark = FAR_Remark.Replace("≥", "%E2%89%A5");


                    DynamicObject CURRENCY = entity["CURRENCYID"] as DynamicObject;//币别
                    string CurrencyId = "";
                    string CurrencyNo = "";
                    string CurrencyName = "";
                    if (CURRENCY != null)
                    {
                        CurrencyId = CURRENCY["ID"].ToString();
                        CurrencyNo = CURRENCY["Number"].ToString();
                        CurrencyName = Convert.ToString(CURRENCY["Name"]);
                    }

                    int Offset = 0;
                    if (!entity["F_DEV_Offset"].IsNullOrEmptyOrWhiteSpace())
                    {
                        Offset = Convert.ToInt32(entity["F_DEV_Offset"].ToString());//是否定制
                    }


                    int HEADDELIVERYWAYID = 0;
                    string HEADDELIVERYWAYNo = "";//交货方式编码
                    DynamicObject HEADDELIVERYWAY = entity["F_RDLV_HEADDELIVERYWAY"] as DynamicObject;//交货方式
                    int DELIVERYWAY = 0;//CRM交货方式枚举
                    if (HEADDELIVERYWAY != null)
                    {
                        HEADDELIVERYWAYNo = HEADDELIVERYWAY["FNUMBER"].ToString();
                    }
                    if (HEADDELIVERYWAYNo == "JHFS02_SYS")
                    {
                        DELIVERYWAY = 1;
                    }
                    int CustomerId = 0;//客户内码
                    string CustomerNo = "";//客户编码
                    string CustomerName = "";//客户名称
                    DynamicObject Customer = entity["CUSTOMERID"] as DynamicObject;//客户
                    if (Customer != null)
                    {
                        CustomerId = Convert.ToInt32(Customer["Id"]);
                        CustomerNo = Convert.ToString(Customer["Number"]); //客户编码
                        CustomerName = Convert.ToString(Customer["Name"]);//客户名称
                    }
                    string sqlCust = string.Format(@"/*dialect*/select F_RDLV_CRMId from T_BD_CUSTOMER where FCUSTID = '{0}'", CustomerId);
                    DataTable dtCust = DBUtils.ExecuteDataSet(this.Context, sqlCust).Tables[0];
                    int CRMCustID = 0;
                    if (dtCust != null && dtCust.Rows.Count > 0 && dtCust.Rows[0]["F_RDLV_CRMId"].ToString() != "" && dtCust.Rows[0]["F_RDLV_CRMId"].ToString() != " " && dtCust.Rows[0]["F_RDLV_CRMId"].ToString() != null)
                    {
                        CRMCustID = Convert.ToInt32(dtCust.Rows[0]["F_RDLV_CRMId"]);
                    }

                    int PayConditonId = 0;//收款条件内码
                    string PayConditonNo = "";//收款条件编码
                    string PayConditonName = "";//收款条件名称
                    DynamicObject PayConditon = entity["PayConditon"] as DynamicObject;//收款条件
                    if (PayConditon != null)
                    {
                        PayConditonId = Convert.ToInt32(PayConditon["Id"]);
                        PayConditonNo = Convert.ToString(PayConditon["Number"]); //收款条件编码
                        PayConditonName = Convert.ToString(PayConditon["Name"]);//收款条件名称
                    }

                    int StockerId = 0;//仓管员内码
                    string StockerNo = "";//仓管员编码
                    string StockerName = "";//仓管员编码
                    DynamicObject Stocker = entity["F_RDLV_StockerID"] as DynamicObject;//仓管员
                    if (Stocker != null)
                    {
                        StockerId = Convert.ToInt32(Stocker["Id"]);
                        StockerNo = Convert.ToString(Stocker["FStaffNumber"]); //仓管员编码
                        StockerName = Convert.ToString(Stocker["Name"]);//仓管员名称
                    }

                    int CarrierId = 0;//承运商内码
                    string CarrierNo = "";//承运商编码
                    string CarrierName = "";//承运商名称
                    DynamicObject Carrier = entity["F_RDLV_CarrierID"] as DynamicObject;//承运商
                    if (Carrier != null)
                    {
                        CarrierId = Convert.ToInt32(Carrier["Id"]);
                        CarrierNo = Convert.ToString(Carrier["Number"]); //承运商编码
                        CarrierName = Convert.ToString(Carrier["Name"]);//承运商名称
                    }
                    string CarriageNO = entity["F_RDLV_CarriageNO"].ToString();//运输单号
                    string OutBoundFID = "";//出库单FID

                    int DeliveryDeptId = 0;//发货部门内码
                    string DeliveryDeptNo = "";//发货部门编码
                    string DeliveryDeptName = "";//发货部门名称
                    DynamicObject DeliveryDept = entity["F_RDLV_DeliveryDeptID"] as DynamicObject;//发货部门
                    if (DeliveryDept != null)
                    {
                        DeliveryDeptId = Convert.ToInt32(DeliveryDept["Id"]);
                        DeliveryDeptNo = Convert.ToString(DeliveryDept["Number"]); //发货部门编码
                        DeliveryDeptName = Convert.ToString(DeliveryDept["Name"]);//发货部门名称
                    }

                    int FMatchMethodID = 0;
                    if (!entity["F_RDLV_WriteOff"].IsNullOrEmptyOrWhiteSpace())
                    {
                        FMatchMethodID = Convert.ToInt32(entity["F_RDLV_WriteOff"]);//核销方式
                    }


                    var PAYABLEFIN = entity["AP_PAYABLEFIN"] as DynamicObjectCollection;
                    int SettleTypeId = 0;//结算方式内码
                    string SettleTypeNo = "";//结算方式编码
                    string SettleTypeName = "";//结算方式名称
                    decimal ExchangeRate = 0;
                    if (PAYABLEFIN != null)
                    {

                        DynamicObject SettleType = PAYABLEFIN[0]["FSettleTypeID"] as DynamicObject;//结算方式
                        if (SettleType != null)
                        {
                            SettleTypeId = Convert.ToInt32(SettleType["Id"]);
                            SettleTypeNo = Convert.ToString(SettleType["Number"]); //结算方式编码
                            SettleTypeName = Convert.ToString(SettleType["Name"]);//结算方式名称
                        }
                        ExchangeRate = Convert.ToDecimal(PAYABLEFIN[0]["FExchangeRate"]);//汇率
                    }

                    string OrderTypeNo = "";//销售类型编码
                    string OrderTypeName = "";//销售类型名称
                    DynamicObject OrderType = entity["F_DEV_OrderType"] as DynamicObject;//销售类型
                    if (OrderType != null)
                    {
                        OrderTypeNo = Convert.ToString(OrderType["Number"]); //销售类型编码
                        OrderTypeName = Convert.ToString(OrderType["Name"]);//销售类型名称
                    }
                    string CRMNumber = Convert.ToString(entity["F_DEV_CRMNumber"]);//CRM编码
                    string JCBM = Convert.ToString(entity["F_RDLV_JCBH"]);//进仓编码
                    string SaleBodyNo = "";//销售类型编码
                    string SaleBodyName = "";//销售类型名称
                    DynamicObject SaleBody = entity["F_RDLV_saleBody"] as DynamicObject;//销售主体
                    if (SaleBody != null)
                    {
                        SaleBodyNo = Convert.ToString(SaleBody["Number"]); //销售主体编码
                        SaleBodyName = Convert.ToString(SaleBody["Name"]);//销售主体名称
                    }
                    string InvoiceNo = Convert.ToString(entity["F_QLTK_InvoiceNo"]);//形式发票
                    string ContractNumber = Convert.ToString(entity["F_QLTK_ContractNumber"]);//合同号

                    string PaymentMethodNo = "";
                    string PaymentMethodName = "";
                    DynamicObject PaymentMethod = entity["F_QLTK_PaymentMethod"] as DynamicObject;//付款方式
                    if (PaymentMethod != null)
                    {
                        PaymentMethodNo = Convert.ToString(PaymentMethod["Number"]); //付款方式编码
                        PaymentMethodName = Convert.ToString(PaymentMethod["Name"]);//付款方式名称
                    }
                    decimal FALLAMOUNTFOR = 0;//价税合计(单据头合计)
                    FALLAMOUNTFOR = Convert.ToDecimal(entity["FALLAMOUNTFOR"]);
                    string ReceivablePlanId = "";//收款计划内码 
                    //查询收款计划内码
                    string sqlSKJH = string.Format(@"/*dialect*/select FENTRYID from t_AR_receivablePlan where FID = '{0}'", FID);
                    DataTable dtSKJH = DBUtils.ExecuteDataSet(this.Context, sqlSKJH).Tables[0];
                    if (dtSKJH.Rows.Count > 0&& dtSKJH!=null)
                    {
                        ReceivablePlanId = Convert.ToString(dtSKJH.Rows[0]["FENTRYID"]);
                    }
                    

                    DynamicObjectCollection FEntityDetail = entity["AP_PAYABLEENTRY"] as DynamicObjectCollection;//明细 

                    List<FinancialReceivablesModel.detailList> detailList = new List<FinancialReceivablesModel.detailList>();//明细数据组
                    string NewStockOrgId = "";//发货组织内码
                    string NewStockOrgNo = "";//发货组织编码
                    string ZgFID = "";//暂估内码
                    string ZgFENTRYID = "";//暂估明细内码
                    string ZgFBillNo = "";//暂估编码
                    int zfys = 0;//正负应收[0:负应收单,1:正应收单]
                    foreach (var item in FEntityDetail)
                    {
                        string FENTRTYID = Convert.ToString(item["id"]);
                        SOURCETYPE = item["FSOURCETYPE"].ToString();//源单类型 
                        //查询暂估应收信息
                        string sqlZgLK = string.Format(@"/*dialect*/select FSBILLID, FSID from t_AR_receivableEntry_LK where FRULEID = 'AP_HookRecToFinRec' and FENTRYID = {0}", FENTRTYID);
                        DataTable dtZgLK = DBUtils.ExecuteDataSet(this.Context, sqlZgLK).Tables[0];
                        if (dtZgLK.Rows.Count > 0)
                        {
                            ZgFENTRYID = Convert.ToString(dtZgLK.Rows[0]["FSID"]);
                            ZgFID = Convert.ToString(dtZgLK.Rows[0]["FSBILLID"]);
                        }
                        string sqlLK = "";//查询暂估应收上游出库/退货信息
                        if (FALLAMOUNTFOR<0)//负数应收
                        {
                            zfys = 0;
                            sqlLK = string.Format(@"/*dialect*/select FSBILLID, FSID from t_AR_receivableEntry_LK where FRULEID='AR_ReturnToReceivableMap' and FENTRYID = {0}", FENTRTYID);
                        }
                        else
                        {
                            zfys = 1;
                            sqlLK = string.Format(@"/*dialect*/select FSBILLID, FSID from t_AR_receivableEntry_LK where FRULEID = 'AR_OutStockToReceivableMap'  and FENTRYID = {0}", FENTRTYID);
                        }  
                        DataTable dtLK = DBUtils.ExecuteDataSet(this.Context, sqlLK).Tables[0];
                        string OutBoundFENTRTYID = "";//销售出库/退货单FENTRTYID
                        if (dtLK.Rows.Count > 0)
                        {
                            OutBoundFENTRTYID = Convert.ToString(dtLK.Rows[0]["FSID"]);
                            OutBoundFID = Convert.ToString(dtLK.Rows[0]["FSBILLID"]);
                        }
                        
                        string MaterialId = "";//物料内码
                        string MaterialNo = "";//物料编码
                        string MaterialName = "";//物料名称
                        DynamicObject Material = item["MATERIALID"] as DynamicObject;//物料
                        if (Material != null)
                        {
                            MaterialId = Convert.ToString(Material["Id"]);
                            MaterialNo = Convert.ToString(Material["Number"]); //物料编码
                            MaterialName = Convert.ToString(Material["Name"]); //物料名称
                        }
                        //查询规格型号
                        string sqlMaterial = string.Format(@"/*dialect*/select FSPECIFICATION from T_BD_MATERIAL_L where FMATERIALID='{0}' and FLOCALEID=2052", MaterialId);
                        DataTable dtMaterial = DBUtils.ExecuteDataSet(this.Context, sqlMaterial).Tables[0];
                        string SPECIFICATION = "";//规格型号
                        if (dtMaterial.Rows.Count>0&& dtMaterial!=null)
                        {
                            SPECIFICATION = Convert.ToString(dtMaterial.Rows[0]["FSPECIFICATION"]);
                        }

                        decimal TaxPrice = Convert.ToDecimal(item["TaxPrice"]);//含税单价
                        string IsFree = Convert.ToString(item["IsFree"]);//是否赠品
                        int ZP = 0;
                        if (IsFree == "true")
                        {
                            ZP = 1;
                        }
                        decimal EntryTaxRate = Convert.ToDecimal(item["EntryTaxRate"]);//税率
                        decimal SalQty = Convert.ToDecimal(item["SalQty"]);//销售数量
                        decimal FALLAMOUNTFOR_D = Convert.ToDecimal(item["FALLAMOUNTFOR_D"]);//价税合计
                        string FLotNO = "";
                        DynamicObject FLot = item["FLot"] as DynamicObject;//批号
                        if (FLot != null)
                        {
                            FLotNO = Convert.ToString(FLot["Number"]);//批号
                        }
                        string SalUnitId = "";//销售单位内码
                        string SalUnitNo = "";//销售单位编码
                        DynamicObject SalUnit = item["SalUnitId"] as DynamicObject;//销售单位
                        if (SalUnit != null)
                        {
                            SalUnitId = Convert.ToString(SalUnit["Id"]);
                            SalUnitNo = Convert.ToString(SalUnit["Number"]); //销售单位编码
                        }

                        string PriceUnitId = "";//计价单位内码
                        string PriceUnitNo = "";//计价单位编码
                        DynamicObject PriceUnit = item["PRICEUNITID"] as DynamicObject;//计价单位单位
                        if (PriceUnit != null)
                        {
                            PriceUnitId = Convert.ToString(PriceUnit["Id"]);
                            PriceUnitNo = Convert.ToString(PriceUnit["Number"]); //计价单位编码
                        }

                        string StockId = "";//仓库内码
                        string StockNo = "";//仓库编码
                        DynamicObject Stock = item["F_RDLV_Stock"] as DynamicObject;//仓库
                        if (Stock != null)
                        {
                            StockId = Convert.ToString(Stock["Id"]);
                            StockNo = Convert.ToString(Stock["Number"]); //仓库编码
                        }


                        DynamicObject NewStockOrg = item["F_RDLV_NewStockOrgId"] as DynamicObject;//发货组织
                        if (NewStockOrg != null)
                        {
                            NewStockOrgId = Convert.ToString(NewStockOrg["Id"]);
                            NewStockOrgNo = Convert.ToString(NewStockOrg["Number"]); //发货组织编码
                        }

                        DynamicObject StockOrg = item["F_RDLV_NewStockOrgId"] as DynamicObject;//库存组织
                        if (StockOrg != null)
                        {
                            StockOrgNo = Convert.ToString(StockOrg["Number"]); //库存组织编码
                        }
                        //基本数量
                        decimal BaseQty = 0;
                        BaseQty = Convert.ToDecimal(item["SalBaseQty"]);
                        decimal PriceQty = Convert.ToDecimal(item["PriceQty"]);

                        string SOURCEBILLTYPEID = "";
                        string SOURCEBILLTYPENo = "";
                        DynamicObject SOURCEBILLTYPE = item["SOURCEBILLTYPEID"] as DynamicObject;//源单单据类型
                        if (SOURCEBILLTYPE != null)
                        {
                            SOURCEBILLTYPEID = Convert.ToString(SOURCEBILLTYPE["ID"]); //源单单据类型内码
                            SOURCEBILLTYPENo = Convert.ToString(SOURCEBILLTYPE["Number"]); //源单单据类型编码
                        }

                        string OUTSTOCKNo = "";
                        DynamicObject OUTSTOCK = item["OUTSTOCKID"] as DynamicObject;//出库单号
                        if (OUTSTOCK != null)
                        {
                            OUTSTOCKNo = Convert.ToString(OUTSTOCK["ID"]); //出库单号编码
                        }
                        string OutBillNo = Convert.ToString(item["F_RDLV_OutBillNo"]);//出库单号

                        decimal SeaAirFreight = Convert.ToDecimal(item["F_QLTK_SeaAirFreight"]);//海空运费
                        decimal PREMIUM = Convert.ToDecimal(item["F_QLTK_PREMIUM"]);//保费
                        decimal Commission = Convert.ToDecimal(item["F_QLTK_Commission"]);//佣金
                        decimal Other1 = Convert.ToDecimal(item["F_QLTK_Other1"]);//其他1
                        int WhetherToRebate = 0;
                        //if (item["F_QLTK_WhetherToRebate"]!=null&&Convert.ToString(item["F_QLTK_WhetherToRebate"])!="" && Convert.ToString(item["F_QLTK_WhetherToRebate"]) != " ")
                        if (!item["F_QLTK_WhetherToRebate"].IsNullOrEmptyOrWhiteSpace())
                        {
                            WhetherToRebate = Convert.ToInt32(item["F_QLTK_WhetherToRebate"]);//是否返利

                        }
                        string Seq = Convert.ToString(item["Seq"]);//行号
                        string MtoNo = Convert.ToString(item["F_QLTK_MtoNo"]);//计划跟踪号

                        string ORDERENTRYSEQ = Convert.ToString(item["ORDERENTRYSEQ"]);//销售订单行号
                        string ORDERENTRYID = Convert.ToString(item["ORDERENTRYID"]);//销售订单明细内码
                        string NoticeNumber = Convert.ToString(item["F_QLTK_NoticeNo"]);//通知单编码
                        decimal EntryDiscountRate = Convert.ToDecimal(item["EntryDiscountRate"]);//折扣率
                        decimal DISCOUNTAMOUNTFOR = Convert.ToDecimal(item["FDISCOUNTAMOUNTFOR"]);//折扣额

                        //订单费用信息
                        decimal OrderSeaAirFreight = 0;//订单海空运费
                        decimal OrderPREMIUM =0;//订单保费
                        decimal OrderCommission = 0;//订单佣金
                        decimal OrderOther1 =0;//订单其他1
                        string sqlOrder= string.Format(@"/*dialect*/select F_QLTK_SeaAirFreight,F_QLTK_PREMIUM,F_QLTK_Commission,F_QLTK_Other1 from T_SAL_ORDERENTRY where  FENTRYID = {0}", ORDERENTRYID);
                        DataTable dtOrder = DBUtils.ExecuteDataSet(this.Context, sqlOrder).Tables[0];
                        if (dtOrder.Rows.Count>0 && dtOrder!=null)
                        {
                            OrderSeaAirFreight = Convert.ToDecimal(dtOrder.Rows[0]["F_QLTK_SeaAirFreight"]);//订单海空运费
                            OrderPREMIUM = Convert.ToDecimal(dtOrder.Rows[0]["F_QLTK_PREMIUM"]);//订单保费
                            OrderCommission = Convert.ToDecimal(dtOrder.Rows[0]["F_QLTK_Commission"]);//订单佣金
                            OrderOther1 = Convert.ToDecimal(dtOrder.Rows[0]["F_QLTK_Other1"]);//订单其他1
                        }
                        string SourceBillNo = Convert.ToString(item["SourceBillNo"]);//源单编号
                        #region 应收单detail数组
                        FinancialReceivablesModel.operate operate = new FinancialReceivablesModel.operate();
                        operate.action = "SaveOrUpdate";

                        FinancialReceivablesModel.dataList dataList = new FinancialReceivablesModel.dataList();
                        dataList.ck = StockId;
                        dataList.ydflnm = ZgFENTRYID;
                        dataList.ydbm = SourceBillNo;
                        dataList.ddmxxh = FENTRTYID;
                        dataList.cpbm = MaterialNo;
                        dataList.hsdj = TaxPrice;
                        dataList.sfzp = ZP;
                        dataList.sl = EntryTaxRate;
                        dataList.xssl = SalQty;
                        dataList.pch = FLotNO;
                        dataList.xsdw = SalUnitNo;
                        dataList.jjdw = PriceUnitNo;
                        dataList.kczz = StockOrgNo;
                        dataList.jszz = SettleOrgNo;
                        dataList.cpmc = MaterialName;
                        dataList.jshj = FALLAMOUNTFOR_D;
                        dataList.ckdmx = ZgFID;
                        dataList.ckd = OutBillNo;
                        dataList.djzj = FENTRTYID;
                        dataList.erpckdnm = ZgFENTRYID;
                        dataList.ckdmxnm = ZgFENTRYID;
                        dataList.jbsl = BaseQty;
                        dataList.yddjlx = SOURCEBILLTYPEID;
                        dataList.ckdh = OutBillNo;
                        dataList.zgysydbm = OutBillNo;
                        dataList.ggxh = SPECIFICATION;
                        dataList.hkyf = SeaAirFreight;
                        dataList.yj = Commission;
                        dataList.bf = PREMIUM;
                        dataList.qt1 = Other1;
                        dataList.sfcyfl = WhetherToRebate;
                        dataList.sczlh = MtoNo;
                        dataList.ddxh = ORDERENTRYSEQ;
                        dataList.ddmxnm = ORDERENTRYID;
                        dataList.xsddh = OrderNo;
                        dataList.jjsl = PriceQty;
                        if (FALLAMOUNTFOR < 0 )
                        {
                            dataList.fckdmxid = OutBoundFENTRTYID;
                            dataList.tkdh = OutBillNo;
                        }
                        else
                        {
                            dataList.fckdmxid = null;
                            dataList.tkdh = null;
                        }

                        dataList.zk = EntryDiscountRate;
                        dataList.zke = DISCOUNTAMOUNTFOR;
  
                        //dataList.yddhkyf = OrderSeaAirFreight;
                        //dataList.yddbf = OrderPREMIUM;
                        //dataList.yddyj = OrderCommission;
                        //dataList.yddqt1 = OrderOther1;

                        FinancialReceivablesModel.detailList detailList1 = new FinancialReceivablesModel.detailList();
                        detailList1.operate = operate;
                        detailList1.data = dataList;
                        detailList.Add(detailList1);

                        #endregion
                    }
                    #region 应收单mainTable数组
                    FinancialReceivablesModel.mainTableList mainTable = new FinancialReceivablesModel.mainTableList();
                    mainTable.sfdc = Survive;
                    mainTable.djnm = FID;
                    mainTable.djbh = FBillNo;
                    mainTable.ddbh = OrderNo;                 
                    mainTable.xsbm = SaleDeptNo;
                    mainTable.xsy = SalerNo;
                    mainTable.xszz = SaleOrgNo;
                    mainTable.rq = FDATE;
                    mainTable.skzz = PayOrgNo;
                    mainTable.jszz = SettleOrgNo;
                    mainTable.jhdd = HeadLocationNo;
                    mainTable.sfdhdd = Seasoning;
                    mainTable.bz = FAR_Remark;
                    mainTable.jsbb = CurrencyName;
                    mainTable.sfdz = Offset;
                    mainTable.jhfs = DELIVERYWAY;
                    mainTable.khmc = CRMCustID;
                    mainTable.sktj = PayConditonNo;
                    mainTable.jsfs = SettleTypeNo;
                    mainTable.cgy = StockerId;
                    mainTable.cys = CarrierNo;
                    mainTable.ysdh = CarriageNO;
                    mainTable.skjhnm = ReceivablePlanId;
                    mainTable.ysje = FALLAMOUNTFOR;
                    mainTable.xslx = OrderTypeNo;
                    mainTable.xszt = SaleBodyNo;
                    mainTable.jcbm = JCBM;
                    mainTable.hxfs = FMatchMethodID;
                    mainTable.zfysd = zfys;

                    mainTable.fph = InvoiceNo;
                    mainTable.hth = ContractNumber;
                    mainTable.hl = ExchangeRate;
                    mainTable.fkfs = PaymentMethodNo;
                    #endregion


                    if ((this.FormOperation.Operation.ToUpper() == "AUDIT"|| this.FormOperation.Operation.ToUpper() == "RELOADFINANCIALRECEIVABLES")&& WhetherPushCRM=="1")
                    {
                        string resultSearch = CRMSearchReceivable(FID, SalerNo);
                        //不存在数据，需要新增
                        if (resultSearch == "无结果")
                        {
                            Return resultAdd = CRMAddReceivable(mainTable, detailList, SalerNo);
                            if (resultAdd.status == "1")
                            {
                                #region 财务应收写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = FBillNo;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "新增应收帐单";
                                interfaceLog.FInvokeType = "";
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "成功";
                                interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"" + SalerNo + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAdd.datajson);
                                interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"" + SalerNo + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturn = JsonConvert.SerializeObject(resultAdd.datajson);
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                //更新单据
                                string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                                sqlList.Add(updateSql);
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                            }
                            else
                            {
                                #region 财务应收单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = FBillNo;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "新增应收帐单";
                                interfaceLog.FInvokeType = "";
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "失败";
                                interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"" + SalerNo + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAdd.datajson);
                                interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"" + SalerNo + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturn = JsonConvert.SerializeObject(resultAdd.datajson);
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                //更新单据
                                string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                                sqlList.Add(updateSql);
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                                throw new KDBusinessException("", resultAdd.datajson);
                            }
                        }
                        //存在数据，需要更新
                        else if (resultSearch == FID)
                        {
                            Return resultAUpdate = CRMUpdateReceivable(mainTable, detailList, SalerNo);
                            if (resultAUpdate.status == "1")
                            {
                                #region 财务应收单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = FBillNo;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "更新应收帐单";
                                interfaceLog.FInvokeType = "";
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "成功";
                                interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"" + SalerNo + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAUpdate.datajson);
                                interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"" + SalerNo + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturn = JsonConvert.SerializeObject(resultAUpdate.datajson);
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                //更新单据
                                string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                                sqlList.Add(updateSql);
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                            }
                            else
                            {
                                #region 财务应收单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = FBillNo;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "更新应收帐单";
                                interfaceLog.FInvokeType = "";
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "失败";
                                interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"" + SalerNo + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturnData = JsonConvert.SerializeObject(resultAUpdate.datajson);
                                interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"" + SalerNo + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                                interfaceLog.FReturn = JsonConvert.SerializeObject(resultAUpdate.datajson);
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                //更新单据
                                string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                                sqlList.Add(updateSql);
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                                throw new KDBusinessException("", resultAUpdate.datajson);
                            }
                        }
                        else
                        {
                            #region 财务应收单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                            Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                            interfaceLog.FBILLNO = FBillNo;
                            interfaceLog.FBILLID = FID;
                            interfaceLog.FDATE = System.DateTime.Now;
                            interfaceLog.FINTERNAME = "更新应收帐单";
                            interfaceLog.FInvokeType = "";
                            interfaceLog.Ftoken = "";
                            interfaceLog.FSTATUS = "失败";
                            interfaceLog.FRequsetData = "{\"data\":[{\"operationinfo\":{\"operator\":\"" + SalerNo + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturnData = resultSearch;
                            interfaceLog.FRequest = "{\"data\":[{\"operationinfo\":{\"operator\":\"" + SalerNo + "\",\"operationDate\":\"" + DateTime.Now.ToString("yyyy-MM-dd") + "\",\"operationTime\":\"" + DateTime.Now.ToString("HH:mm:ss") + "\"},\"mainTable\":" + JsonConvert.SerializeObject(mainTable) + ",\"detail1\":" + JsonConvert.SerializeObject(detailList) + "}],\"header\":{\"systemid\":\"kingde\",\"" + DateTime.Now + "\":\"currentTimeTamp \",\"Md5\":\"\"}}";
                            interfaceLog.FReturn = resultSearch;
                            string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                            List<string> sqlList = new List<string>();
                            if (!string.IsNullOrEmpty(LogSql))
                            {
                                sqlList.Add(LogSql);
                            }
                            //更新单据
                            string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, interfaceLog.FSTATUS, FID);
                            sqlList.Add(updateSql);
                            DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                            #endregion
                            throw new KDBusinessException("", resultSearch);
                        }
                    }
                    else if (this.FormOperation.Operation.ToUpper() == "DELETE"  && WhetherPushCRM == "1")
                    {
                        if (FSTATUS == "成功")
                        {
                            string resultSearch = CRMSearchReceivable(FID, SalerNo);
                            //存在数据，需要新增
                            if (resultSearch == FID)
                            {
                                string resultDelete = CRMDeleteReceivable(FID, SalerNo);
                                if (resultDelete == "删除成功")
                                {
                                    #region 财务应收单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                    Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                    interfaceLog.FBILLNO = FBillNo;
                                    interfaceLog.FBILLID = FID;
                                    interfaceLog.FDATE = System.DateTime.Now;
                                    interfaceLog.FINTERNAME = "删除应收帐单";
                                    interfaceLog.FInvokeType = "";
                                    interfaceLog.Ftoken = "";
                                    interfaceLog.FSTATUS = "成功";
                                    interfaceLog.FRequsetData = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                                    interfaceLog.FReturnData = resultDelete;
                                    interfaceLog.FRequest = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                                    interfaceLog.FReturn = resultDelete;
                                    string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                    List<string> sqlList = new List<string>();
                                    if (!string.IsNullOrEmpty(LogSql))
                                    {
                                        sqlList.Add(LogSql);
                                    }
                                    DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                    #endregion
                                }
                                else
                                {
                                    #region 财务应收单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                    Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                    interfaceLog.FBILLNO = FBillNo;
                                    interfaceLog.FBILLID = FID;
                                    interfaceLog.FDATE = System.DateTime.Now;
                                    interfaceLog.FINTERNAME = "删除应收帐单";
                                    interfaceLog.FInvokeType = "";
                                    interfaceLog.Ftoken = "";
                                    interfaceLog.FSTATUS = "失败";
                                    interfaceLog.FRequsetData = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                                    interfaceLog.FReturnData = resultDelete;
                                    interfaceLog.FRequest = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                                    interfaceLog.FReturn = resultDelete;
                                    string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                    List<string> sqlList = new List<string>();
                                    if (!string.IsNullOrEmpty(LogSql))
                                    {
                                        sqlList.Add(LogSql);
                                    }
                                    //更新单据
                                    string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, "删除失败", FID);
                                    sqlList.Add(updateSql);
                                    DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                    #endregion
                                    throw new KDBusinessException("", "单据同步删除CRM失败，禁止删除");
                                }
                            }
                            else if (resultSearch.Contains("操作者未找到"))
                            {
                                #region 财务应收单写日志(插入一张CRM接口日志单据，更新单据上的接口调用方式/调用时间/调用结果）
                                Common.InterfaceLog interfaceLog = new Common.InterfaceLog();
                                interfaceLog.FBILLNO = FBillNo;
                                interfaceLog.FBILLID = FID;
                                interfaceLog.FDATE = System.DateTime.Now;
                                interfaceLog.FINTERNAME = "删除应收帐单";
                                interfaceLog.FInvokeType = "";
                                interfaceLog.Ftoken = "";
                                interfaceLog.FSTATUS = "失败";
                                interfaceLog.FRequsetData = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                                interfaceLog.FReturnData = resultSearch;
                                interfaceLog.FRequest = "{\"operationinfo\":{\"operator\":\"" + SalerNo + "\"},\"mainTable\":{\"djbm\":\"" + FBillNo + "\"},\"header\":{\"systemid\":\"kingdee\",\"currentDateTime\":\"" + DateTime.Now + "\",\"Md5\":\"md5OfStr \"}}";
                                interfaceLog.FReturn = resultSearch;
                                string LogSql = interfaceLog.WriteCRMLogSql();//获取写入日志单据的SQL
                                List<string> sqlList = new List<string>();
                                if (!string.IsNullOrEmpty(LogSql))
                                {
                                    sqlList.Add(LogSql);
                                }
                                //更新单据
                                string updateSql = string.Format(@"/*dialect*/ update t_AR_receivable set F_DEV_FDATE='{0}',F_DEV_FSTATUS='{1}' 
                    where FID={2}", interfaceLog.FDATE, "删除失败", FID);
                                sqlList.Add(updateSql);
                                DBServiceHelper.ExecuteBatch(this.Context, sqlList);
                                #endregion
                                throw new KDBusinessException("", resultSearch);
                            }
                        }


                    }
                }
            }
        }

        /// <summary>
        /// api配置
        /// </summary>
        public DataTable APISetting(string InterfaceName)
        {
            string Sql = string.Format(@"select * from RDLV_t_CRMInterface where F_RDLV_InterfaceName='{0}'", InterfaceName);
            return DBServiceHelper.ExecuteDataSet(this.Context, Sql).Tables[0];
        }


        /// <summary>
        /// CRM新增应收帐单接口
        /// </summary>
        public Return CRMAddReceivable(FinancialReceivablesModel.mainTableList mainTable, List<FinancialReceivablesModel.detailList> detail1, string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/saveOrUpdateModeData/create_outbound_order";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting("新增应收帐单");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            Return result = PostToPushNews(requestUri1, systemid, currentTimeTamp, md5OfStr, mainTable, detail1, UserAccount);


            return result;
        }

        /// <summary>
        /// CRM更新应收帐单接口
        /// </summary>
        public Return CRMUpdateReceivable(FinancialReceivablesModel.mainTableList mainTable, List<FinancialReceivablesModel.detailList> detail1, string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/saveOrUpdateModeData/update_outbound_order";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting("更新应收帐单");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            Return result = PostToUpdateNews(requestUri1, systemid, currentTimeTamp, md5OfStr, mainTable, detail1, UserAccount);


            return result;
        }




        /// <summary>
        /// CRM查询应收帐单接口
        /// </summary>
        public string CRMSearchReceivable(string djnm, string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/getDataByPK/select_outbound_order";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting("查询应收帐单");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            string result = PostToSearchNews(requestUri1, systemid, currentTimeTamp, md5OfStr, djnm, UserAccount);


            return result;
        }

        /// <summary>
        /// CRM删除出库单接口
        /// </summary>
        public string CRMDeleteReceivable(string djnm, string UserAccount)
        {
            //当前日期
            String currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            //当前时间
            String currentTime = DateTime.Now.ToString("hh:mm:ss");

            string requestUri1 = "http://10.10.17.127:8086/api/cube/restful/interface/deleteModeDataByPK/delete_outbound_order";

            //系统标识
            String systemid = "kingdee";
            //密码
            String d_password = "p@ssw0rd...";
            DataTable dt = APISetting("删除应收帐单");
            if (dt.Rows.Count > 0)
            {
                requestUri1 = Convert.ToString(dt.Rows[0]["F_RDLV_URL"]);
                systemid = Convert.ToString(dt.Rows[0]["F_RDLV_SystemId"]);
                d_password = Convert.ToString(dt.Rows[0]["F_RDLV_Password"]);
            }
            //获取时间戳
            String currentTimeTamp = getTimestamp();
            String md5Source = systemid + d_password + currentTimeTamp;
            String md5OfStr = Md5(md5Source).ToLower();

            string result = PostToDeleteNews(requestUri1, systemid, currentTimeTamp, md5OfStr, djnm, UserAccount);


            return result;
        }

        /// <summary>
        /// md5加密
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static String Md5(string s)
        {
            char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(s);
            byte[] result = md5.ComputeHash(inputBytes);
            int j = result.Length;
            char[] str = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++)
            {
                byte byte0 = result[i];
                str[k++] = hexDigits[byte0 >> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        }

        /// <summary>
        /// CRM查询应收帐单POST
        /// </summary>
        public static string PostToSearchNews(string url, string systemid, string currentTimeTamp, string md5OfStr, string djnm, string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"operationinfo\":{\"operator\":\"CRM\"},\"mainTable\":{\"djnm\":\""+djnm+"\"},\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            //string[] resAry = result.Split(new string[] { "result" }, StringSplitOptions.None);
            //string json = resAry[resAry.Length - 1].Remove(0, 3);
            //json= Regex.Replace(json, "\"\"", "\"");
            //json = json.Remove(json.Length - 2, 2);
            //json = Regex.Unescape(json);
            //if (json == "{}")
            //{
            //    return "无结果";
            //}
            //else
            //{
            //    Dictionary<string, object> dicJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
            //    Dictionary<string, object> mainTableJson = JsonConvert.DeserializeObject<Dictionary<string, object>>(dicJson["mainTable"].ToString());
            //    string returnCode = mainTableJson["djnm"].ToString();
            //    return returnCode;
            //}
            JObject jo = (JObject)JsonConvert.DeserializeObject(result);
            if (jo == null)
            {
                return "无结果";
            }
            else if (jo.ToString().Contains("status"))
            {
                string returnCode = jo["info"].ToString();
                return returnCode;
            }
            else if (jo["result"].ToString() == "{}")
            {
                return "无结果";
            }
            else
            {

                JToken rtToken = jo.SelectToken("result");
                JObject rt = (JObject)JsonConvert.DeserializeObject(rtToken.ToString());
                JToken mtToken = rt.SelectToken("mainTable");
                JObject mt = (JObject)JsonConvert.DeserializeObject(mtToken.ToString());
                string returnCode = mt["djnm"].ToString();
                return returnCode;
            }
        }



        /// <summary>
        /// CRM新增应收帐单POST
        /// </summary>
        public static Return PostToPushNews(string url, string systemid, string currentTimeTamp, string md5OfStr, FinancialReceivablesModel.mainTableList mainTable, List<FinancialReceivablesModel.detailList> detail1, string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"data\":[{\"operationinfo\":{\"operator\":\"CRM\",\"operationDate\":\""+DateTime.Now.ToString("yyyy-MM-dd")+"\",\"operationTime\":\""+DateTime.Now.ToString("HH:mm:ss")+"\"},\"mainTable\":"+JsonConvert.SerializeObject(mainTable)+",\"detail1\":"+JsonConvert.SerializeObject(detail1)+"}],\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Return @return = new Return();
            //string[] sArray = result.Split(new string[] { "}}\",\"status\":\"", "}]" }, StringSplitOptions.None);
            string[] resAry = result.Split(new string[] { "status" }, StringSplitOptions.None);
            string[] json = result.Split(new string[] { "datajson" }, StringSplitOptions.None);
            //if (resAry[resAry.Length - 1].IndexOf("1") > -1)
            //{
            string status = "";
            status = resAry[resAry.Length - 1].Replace("\"", "");
            status = status.Replace(":", "");
            status = status.Replace("}", "");
            string json1 = json[json.Length - 1].Remove(0, 3);
            json1 = Regex.Replace(json1, "\"\"", "\"");
            json1 = json1.Remove(json1.Length - 2, 2);
            json1 = Regex.Unescape(json1);
            json1 = Regex.Unescape(json1);
            //}
            @return.status = status;
            @return.datajson = json1;
            return @return;
        }



        /// <summary>
        /// CRM更新应收帐单POST
        /// </summary>
        public static Return PostToUpdateNews(string url, string systemid, string currentTimeTamp, string md5OfStr, FinancialReceivablesModel.mainTableList mainTable, List<FinancialReceivablesModel.detailList> detail1, string UserAccount)
        {

            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"data\":[{\"operationinfo\":{\"operator\":\"CRM\",\"operationDate\":\""+DateTime.Now.ToString("yyyy-MM-dd")+"\",\"operationTime\":\""+DateTime.Now.ToString("HH:mm:ss")+"\"},\"mainTable\":"+JsonConvert.SerializeObject(mainTable)+",\"detail1\":"+JsonConvert.SerializeObject(detail1)+"}],\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            string b = builder.ToString();
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            Return @return = new Return();
            result = Regex.Unescape(result);//去除转义符
            result = Regex.Unescape(result);//去除转义符
            string rs = JsonConvert.SerializeObject(result);
            string[] resAry = result.Split(new string[] { "status" }, StringSplitOptions.None);
            string[] json = result.Split(new string[] { "datajson" }, StringSplitOptions.None);
            string status = "";
            status = resAry[resAry.Length - 1].Replace("\"", "");
            status = status.Replace(":", "");
            status = status.Replace("}", "");
            string json1 = json[json.Length - 1].Remove(0, 3);
            json1 = Regex.Replace(json1, "\"\"", "\"");
            json1 = Regex.Unescape(json1);
            //}
            @return.status = status;
            @return.datajson = json1;
            return @return;
        }


        /// <summary>
        /// CRM删除应收帐单POST
        /// </summary>
        public static string PostToDeleteNews(string url, string systemid, string currentTimeTamp, string md5OfStr, string djnm, string UserAccount)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>
            {
                {"datajson","{\"operationinfo\":{\"operator\":\"CRM\"},\"mainTable\":{\"djnm\":\""+djnm+"\"},\"header\":{\"systemid\":\""+systemid+"\",\"currentDateTime\":\""+currentTimeTamp+"\",\"Md5\":\""+md5OfStr+"\"}}"}
            };
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            string[] resAry = result.Split(new string[] { "result" }, StringSplitOptions.None);
            string json = resAry[resAry.Length - 1].Remove(0, 3);
            //json = json.Remove(json.Length - 2, 2);
            json = Regex.Unescape(json);
            json = Regex.Replace(json, "\"\"", "\"");
            string[] message = json.Split(new string[] { "message" }, StringSplitOptions.None);

            if (json == "{}")
            {
                return "无结果";
            }
            else
            {

                return message[1].Substring(3, 4);
            }
        }


        /**
       * 获取时间戳   格式如：19990101235959
       * @return
       */
        public static String getTimestamp()
        {

            return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
        }


        /**
       * 接口返回值自定义 
       */
        public class Return
        {
            public string status { get; set; }
            public string datajson { get; set; }
        }
    }
}
